package cn.edu.swufe.surverpark.advice;

import java.util.Map;

import javax.annotation.Resource;

import org.aspectj.lang.ProceedingJoinPoint;

import com.opensymphony.xwork2.ActionContext;

import cn.edu.swufe.surverpark.model.Log;
import cn.edu.swufe.surverpark.model.User;
import cn.edu.swufe.surverpark.struts2.service.LogService;
import cn.edu.swufe.surverpark.util.StringUtil;

/**
 * @author 陈龙 E-mail:529914446@qq.com
 * @version创建时间:2015年5月7日上午3:53:24 类说明
 */
public class Logger {

	@Resource
	LogService logService;

	public Object record(ProceedingJoinPoint pjp) {
		Log log = new Log();
		try {
			ActionContext ac = ActionContext.getContext();

			if (ac != null) {
				Map<String, Object> session = ac.getSession();
				if (session != null) {
					User user = (User) session.get("user");
					if (user != null) {
						log.setOperator("" + user.getId() + ":"
								+ user.getNickName());
					}
				}
			}
			String mname = pjp.getSignature().getName();
			log.setOperName(mname);
			Object[] params = pjp.getArgs();
			String r = StringUtil.arr2Str(params);
			if(r.length() >= 500){
				r = r.substring(0,499);
			}
			log.setOperParams(r);
			Object ret = pjp.proceed();
			log.setOperResult("success");
			if (ret != null)
				log.setResultMsg(ret.toString());
			return ret;
		} catch (Throwable e) {
			log.setOperResult("failure");
			log.setResultMsg(e.getMessage());
		} finally {
			logService.saveEntity(log);
		}

		return null;
	}
}
